import React, { useState, useEffect } from "react";
import axios from "axios";
import { Table, Space, Button, Modal, message, Tree } from "antd";
import { ExclamationCircleOutlined } from "@ant-design/icons";

const { confirm } = Modal;

export default function RoleList() {
  const [dataSource, setDataSource] = useState();
  useEffect(() => {
    fetchDate();
    fetchRoleDate();
  }, []);

  const fetchDate = async () => {
    const { data } = await axios.get("/roles");
    console.log(data);
    setDataSource(data);
  };

  const [treeData, setTreeData] = useState([]);
  const fetchRoleDate = async () => {
    const { data } = await axios.get("/rights?_embed=children");
    console.log(data);
    setTreeData(data);
  };

  // 删除
  const deleteMethod = (item) => {
    console.log(item);
    const fetchDdlDate = async () => {
      const res = await axios.delete(`/roles/${item.id}`);
      if (res.status === 200) {
        fetchDate();
        message.success("删除成功");
      }
    };
    fetchDdlDate();
  };

  const delConfirm = (item) => {
    confirm({
      title: "提示",
      icon: <ExclamationCircleOutlined />,
      content: "确定要删除吗？",
      okText: "确认",
      cancelText: "取消",
      onOk() {
        console.log("OK");
        deleteMethod(item);
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };

  const columns = [
    {
      title: "ID",
      dataIndex: "id",
    },
    {
      title: "角色名称",
      dataIndex: "roleName",
    },
    {
      title: "操作",
      key: "action",
      render: (item) => (
        <Space size="middle">
          <Button
            type="primary"
            size="small"
            ghost
            onClick={() => showModal(item)}
          >
            编辑
          </Button>
          <Button
            type="primary"
            size="small"
            danger
            ghost
            onClick={() => delConfirm(item)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [currentRoles, setCurrentRoles] = useState([]);
  const [currentId, setCurrentId] = useState(0);
  const showModal = (item) => {
    setCurrentRoles(item.rights);
    setCurrentId(item.id);
    setIsModalVisible(true);
  };

  const handleOk = async () => {
    console.log(currentId);
    console.log(currentRoles);
    const res = await axios.patch(`/roles/${currentId}`, {
      rights: currentRoles,
    });
    if (res.status === 200) {
      message.success("修改成功！");
      setIsModalVisible(false);
      fetchDate();
    }
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const onSelect = (selectedKeys, info) => {
    console.log("selected", selectedKeys, info);
  };

  const onCheck = (checkedKeys, info) => {
    setCurrentRoles(checkedKeys.checked);
    console.log("onCheck", checkedKeys, info);
  };

  return (
    <>
      <Table
        bordered
        dataSource={dataSource}
        columns={columns}
        rowKey={(item) => item.id}
        pagination={{ pageSize: 10 }}
        size="small"
      />
      {/* 角色编辑弹窗 */}
      <Modal
        title="角色权限分配"
        okText="保存"
        cancelText="取消"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Tree
          checkable
          checkStrictly={true}
          onSelect={onSelect}
          onCheck={onCheck}
          treeData={treeData}
          checkedKeys={currentRoles}
        />
      </Modal>
    </>
  );
}
